package com.shxy.cloudclassroom.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(value = {
            VerificationCodeErrorException.class,
            NotfoundVerificationCodeException.class,
            PasswordErrorException.class,
            UserNameAlreadyExistsException.class,
            UserNotfoundException.class
    })
    @ResponseBody
    public Object handleBusinessException(RuntimeException e, HttpServletRequest request, HttpServletResponse response) {
        log.error("业务异常: ", e);
        
        // 判断是否是 AJAX 请求
        boolean isAjaxRequest = isAjaxRequest(request);
        
        if (isAjaxRequest) {
            // AJAX 请求返回 JSON
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            return result;
        } else {
            // 非 AJAX 请求返回错误页面
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error");
            modelAndView.addObject("errorMessage", e.getMessage());
            return modelAndView;
        }
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleSystemException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        log.error("系统异常: ", e);
        
        // 判断是否是 AJAX 请求
        boolean isAjaxRequest = isAjaxRequest(request);
        
        if (isAjaxRequest) {
            // AJAX 请求返回 JSON
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "系统异常，请联系管理员");
            return result;
        } else {
            // 非 AJAX 请求返回错误页面
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error");
            modelAndView.addObject("errorMessage", "系统异常，请联系管理员");
            return modelAndView;
        }
    }

    /**
     * 判断是否是 AJAX 请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header) || 
               request.getRequestURI().startsWith("/") ||
               (request.getHeader("Accept") != null && request.getHeader("Accept").contains("application/json")) ||
               (request.getHeader("Content-Type") != null && request.getHeader("Content-Type").contains("application/json"));
    }
}